package com.hdl.config;

import com.hdl.pojo.Configuration;
import com.hdl.pojo.MappedStatement;
import com.hdl.pojo.SqlType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author hedonglin
 * @date 2020/4/21 21:23
 * @description mapper.xml解析
 */
public class XmlMapperBuilder {
    private Configuration configuration;
    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }
    @SuppressWarnings("unchecked")
    public void parse(InputStream in) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(in);
        // <mapper>
        Element rootElement = document.getRootElement();
        // namespace
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectElements = rootElement.selectNodes("//" + SqlType.SELECT.getCode());
        List<Element> insertElements = rootElement.selectNodes("//"+ SqlType.INSERT.getCode());
        List<Element> updateElements = rootElement.selectNodes("//"+ SqlType.UPDATE.getCode());
        List<Element> deleteElements = rootElement.selectNodes("//"+ SqlType.DELETE.getCode());
        setMappedStatement(configuration, selectElements, namespace, SqlType.SELECT);
        setMappedStatement(configuration, insertElements, namespace, SqlType.INSERT);
        setMappedStatement(configuration, updateElements, namespace, SqlType.UPDATE);
        setMappedStatement(configuration, deleteElements, namespace, SqlType.DELETE);
    }
    /**
     * 将<select /> <insert /> <update /> <delete />标签解析并放入Configuration的mappedStatement中
     */
    private void setMappedStatement(Configuration configuration, List<Element> list, String namespace, SqlType sqlType){
        if (list == null || list.size() == 0){
            return;
        }
        for (Element element : list) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlType(sqlType);
            String key = String.join(".", namespace, id);
            configuration.getMappedStatementMap().put(key ,mappedStatement);
        }
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }

        return null;
    }

}
